//
//  TopicViewController.m
//  miaopai
//
//  Created by Crow Zhang on 15/11/12.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "TopicViewController.h"
#import "SliderButton.h"
#import "CustomerNetworking.h"
#import "NewsTopicModel.h"
#import "NewTopicTableViewCell.h"
#import "TopicDetailViewController.h"
#import <MJRefresh.h>
#import "SCCatWaitingHUD.h"

#define Kheight [[UIScreen mainScreen]bounds].size.height / 667
@interface TopicViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, SliderButtonDelegate>

@property(nonatomic, retain) SliderButton *sliderButton;

@property(nonatomic, retain) UIScrollView *bigScrollView;

@property(nonatomic, retain) UITableView *newsTopicTableView;

@property(nonatomic, retain) UITableView *topAllTableView;

@property(nonatomic, retain) NSMutableArray *newsTopicModelArray;

@property(nonatomic, retain) NSMutableArray *topAllModelArray;

@property(nonatomic, assign) BOOL isPush;

@end

@implementation TopicViewController

- (void)dealloc
{
    [_sliderButton release];
    [_bigScrollView release];
    [_newsTopicTableView release];
    [_topAllModelArray release];
    [_topAllTableView release];
    [_newsTopicModelArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"话题";
    
    [[SCCatWaitingHUD sharedInstance] animateWithInteractionEnabled:YES];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"";
    self.navigationItem.backBarButtonItem = backItem;
    [backItem release];
    
    self.newsTopicModelArray = [NSMutableArray array];
    self.topAllModelArray = [NSMutableArray array];
    
    //创建上方的滑动条
    [self creatSliderButtonView];
    //创建视图
    [self creatSubViews];
    //下载网络数据
    [self downloadNewTopicData];
    [self downloadTopData];
}

#pragma mark 创建上方的滑动条
- (void)creatSliderButtonView
{
    NSArray *btnTitleArray = @[@"新话题榜", @"TOP总榜"];
    self.sliderButton = [[SliderButton alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 40 * Kheight) andBtnTitleArray:nil];
    _sliderButton.btnTitleArray = btnTitleArray;
    _sliderButton.delegate = self;
    [self.view addSubview:_sliderButton];
    [_sliderButton release];
}

#pragma mark 创建底部的大scrollView
- (void)creatSubViews
{
    self.bigScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, _sliderButton.frame.origin.y + _sliderButton.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - _sliderButton.frame.origin.y - _sliderButton.frame.size.height)];
    _bigScrollView.showsHorizontalScrollIndicator = NO;
    _bigScrollView.pagingEnabled = YES;
    _bigScrollView.delegate = self;
    _bigScrollView.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
    _bigScrollView.scrollsToTop = NO;
    [self.view addSubview:_bigScrollView];
    [_bigScrollView release];

#pragma mark 创建刷新按钮
    for (int i = 0; i < 2; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i * _bigScrollView.frame.size.width, 0, _bigScrollView.frame.size.width, _bigScrollView.frame.size.height);
        [button setTitle:@"获取内容失败，点击刷新..." forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:0.5141 green:0.5141 blue:0.5141 alpha:1.0] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        [button addTarget:self action:@selector(refreshContent:) forControlEvents:UIControlEventTouchUpInside];
        [_bigScrollView addSubview:button];
    }
    [self creatNewsTopicSubview];
    [self creatTopAllSubview];
}

- (void)refreshContent:(UIButton *)button
{
    if (_bigScrollView.contentOffset.x == 0) {
        [self addNewsTopicTableViewHeader];
    }else
    {
        [self addTopAllTableViewHeader];
    }
}

#pragma mark 下载数据
- (void)downloadNewTopicData
{
    
    // 新话题榜数据
    [_newsTopicModelArray removeAllObjects];
    [CustomerNetworking customerConnectWithURL:@"http://api.miaopai.com/m/new_topic_rank.json?os=ios&page=1&per=50&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1" andparameters:nil andBlock:^(id response) {
        [[SCCatWaitingHUD sharedInstance] stop];
        NSDictionary *bigDic = response;
        NSArray *resultArray = [bigDic objectForKey:@"result"];
        for (NSDictionary *dic in resultArray) {
            NewsTopicModel *newsTopicModel = [NewsTopicModel newsTopicModelWithDictionary:dic];
            [_newsTopicModelArray addObject:newsTopicModel];
        }
        [_newsTopicTableView reloadData];
        if (_newsTopicModelArray.count != 0) {
            [_newsTopicTableView.mj_header endRefreshing];
        }
    }];
}

- (void)downloadTopData
{
    // TOP总榜数据
    [_topAllModelArray removeAllObjects];
    [CustomerNetworking customerConnectWithURL:@"http://api.miaopai.com/m/topic_rank.json?os=ios&page=1&per=50&unique_id=d148d7c2b9c27f685d9be7639517be5e3661826668&version=6.2.1" andparameters:nil andBlock:^(id response) {
        NSDictionary *bigDic = response;
        NSArray *resultArray = [bigDic objectForKey:@"result"];
        for (NSDictionary *dic in resultArray) {
            NewsTopicModel *newsTopicModel = [NewsTopicModel newsTopicModelWithDictionary:dic];
            [_topAllModelArray addObject:newsTopicModel];
        }
        [_topAllTableView reloadData];
        if (_topAllModelArray.count != 0 ) {
            [_topAllTableView.mj_header endRefreshing];
        }
    }];
}

#pragma mark 创建新话题榜页的tableView
- (void)creatNewsTopicSubview
{
    self.newsTopicTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _bigScrollView.frame.size.width, _bigScrollView.frame.size.height) style:UITableViewStylePlain];
    [_newsTopicTableView setContentInset:UIEdgeInsetsMake(0, 0, 48, 0)];
    _newsTopicTableView.delegate = self;
    _newsTopicTableView.dataSource = self;
    _newsTopicTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [_newsTopicTableView registerClass:[NewTopicTableViewCell class] forCellReuseIdentifier:@"NewTopicTableViewCell"];
    _newsTopicTableView.scrollsToTop = YES;
    [_bigScrollView addSubview:_newsTopicTableView];
    [_newsTopicTableView.tableFooterView release];
    [_newsTopicTableView release];
    [self addNewsTopicTableViewHeader];
}

#pragma mark 给新话题榜页的tableView添加下拉刷新
- (void)addNewsTopicTableViewHeader
{
    _newsTopicTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self downloadNewTopicData];
    }];
    [_newsTopicTableView.mj_header beginRefreshing];
}

#pragma mark 创建TOP总榜的tabelView
- (void)creatTopAllSubview
{
    self.topAllTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, _newsTopicTableView.frame.size.height) style:UITableViewStylePlain];
    [_topAllTableView setContentInset:UIEdgeInsetsMake(0, 0, 48, 0)];
    _topAllTableView.delegate = self;
    _topAllTableView.dataSource = self;
    _topAllTableView.scrollsToTop = NO;
    _topAllTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [_topAllTableView registerClass:[NewTopicTableViewCell class] forCellReuseIdentifier:@"TopAllTableViewCell"];
    [_bigScrollView addSubview:_topAllTableView];
    [_topAllTableView.tableFooterView release];
    [_topAllTableView release];
    [self addTopAllTableViewHeader];
}

#pragma mark 给TOP总榜的tabelView添加下拉刷新
- (void)addTopAllTableViewHeader
{
    _topAllTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self downloadTopData];
    }];
    [_topAllTableView.mj_header beginRefreshing];
}

#pragma mark scrollView的代理事件
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    _sliderButton.buttonTag = _bigScrollView.contentOffset.x / self.view.frame.size.width + 100;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    //NSLog(@"%lf", scrollView.contentOffset.x);
    if (_bigScrollView.contentOffset.x == 0) {
        _newsTopicTableView.scrollsToTop = YES;
        _topAllTableView.scrollsToTop = NO;
    }else if(_bigScrollView.contentOffset.x == kWidth)
    {
        _newsTopicTableView.scrollsToTop = NO;
        _topAllTableView.scrollsToTop = YES;
    }
}

#pragma mark 返回tableView的单元格个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:_newsTopicTableView])
    {
        return _newsTopicModelArray.count;
    }else
    {
        return _topAllModelArray.count;
    }
    
}

#pragma mark 自定义单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_newsTopicTableView]) {
        NewTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewTopicTableViewCell" forIndexPath:indexPath];
        if (_newsTopicModelArray.count > 0) {
            NewsTopicModel *model = [_newsTopicModelArray objectAtIndex:indexPath.row];
            cell.newsTopModel = model;
        }
        
        return cell;
    }else
    {
        NewTopicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopAllTableViewCell" forIndexPath:indexPath];
        if (_topAllModelArray.count > 0) {
            cell.newsTopModel = [_topAllModelArray objectAtIndex:indexPath.row];
        }
        return cell;
    }
}

#pragma mark tableView的单元格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

#pragma mark tabelView的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView isEqual:_newsTopicTableView]) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        TopicDetailViewController *topicDetailViewController = [[TopicDetailViewController alloc] init];
        NewsTopicModel *newsTopicModel = [_newsTopicModelArray objectAtIndex:indexPath.row];
        topicDetailViewController.stpid = newsTopicModel.topic.stpid;
        topicDetailViewController.topicName = newsTopicModel.topic.name;
        [self.navigationController pushViewController:topicDetailViewController animated:YES];
        self.isPush = YES;
        [topicDetailViewController release];
    }else
    {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        TopicDetailViewController *topicDetailViewController = [[TopicDetailViewController alloc] init];
        NewsTopicModel *newsTopicModel = [_topAllModelArray objectAtIndex:indexPath.row];
        topicDetailViewController.stpid = newsTopicModel.topic.stpid;
        topicDetailViewController.topicName = newsTopicModel.topic.name;
        self.isPush = YES;
        [self.navigationController pushViewController:topicDetailViewController animated:YES];
        [topicDetailViewController release];
    }
    
}

#pragma mark sliderButton的代理方法
- (void)buttonOfSliderButtonClicked:(UIButton *)sender
{
    [_bigScrollView setContentOffset:CGPointMake((sender.tag - 100) * self.view.frame.size.width, 0) animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    if (!self.isPush) {
        UIView * view = [self.tabBarController.view.subviews lastObject];
        [UIView animateWithDuration:0.5 animations:^{
            view.frame = CGRectMake(0, kHeight - 48, kWidth, 48);
        }];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    if (self.isPush) {
        self.isPush = NO;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
